import logging
from logging.handlers import RotatingFileHandler
from flaskapp.plugins.SetupYaml import load_yaml_config
import os

def setup_logging(module_name, config_name=None):
    if not config_name:
        # 构建配置文件的完整路径
        log_config = load_yaml_config('log.yaml')

    

    # 构建完整的日志文件路径
    log_directory = log_config['log']['path']
    log_filename = log_config['log']['filename']
    log_path = os.path.join(log_directory, log_filename)

    # 确保日志目录存在
    if not os.path.exists(log_directory):
        os.makedirs(log_directory)

    # 设置日志处理器
    handler = RotatingFileHandler(
        log_path,
        maxBytes=log_config['log']['max_bytes'],
        backupCount=log_config['log']['backup_count']
    )

    # 设置日志级别
    handler.setLevel(log_config['log']['level'])

    # 设置日志格式，其中%(name)s将显示传递给setup_logging的module_name
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    handler.setFormatter(formatter)

    # 创建并配置日志器，使用module_name作为日志器的名称
    logger = logging.getLogger(module_name)
    logger.setLevel(log_config['log']['level'])
    logger.addHandler(handler)

    return logger

# 你需要传递调用模块的名称作为module_name参数
if __name__ == '__main__':
    logger = setup_logging(__name__)
    logger.info('Logging is configured and this is an info message.')